package codeRandomThoughts.Test139单词拆分;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 回溯法
 */
public class Solution2 {
    Set<String> set;
    int[] memo;

    public boolean wordBreak(String s, List<String> wordDict) {
        memo = new int[s.length()];
        set = new HashSet<>(wordDict);
        return backtracking(s, 0);
    }

    private boolean backtracking(String s, int startIndex) {
        //终止条件
        if (startIndex == s.length()) {
            return true;
        }
        if (memo[startIndex] == -1) {
            return false;
        }

        //单层搜索逻辑
        for (int i = startIndex; i < s.length(); i++) {
            String substring = s.substring(startIndex, i + 1);

            //拆分出的单词无法匹配
            if (!set.contains(substring)) {
                continue;
            }
            boolean res = backtracking(s, i + 1);
            if (res) return true;
        }

        memo[startIndex] = -1;
        return false;
    }
}
